import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
  useTransition,
} from 'react';
import {
  PermissionsAndroid,
  Platform,
  ScrollView,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import { useTranslation } from 'react-i18next';
import { RouteProp, useNavigation, useRoute } from '@react-navigation/native';
import { Asset } from 'react-native-image-picker';
import { FormInputField, FormSelectField } from '@/components/FormField';
import { SafeAreaView } from 'react-native-safe-area-context';
import {
  Geolocation,
  setLocatingWithReGeocode,
  setNeedAddress,
} from 'react-native-amap-geolocation';
import SingleSelectBottomSheet from '@/components/SingleSelectBottomSheet';
import { BottomSheetModal } from '@gorhom/bottom-sheet';
import AvatarImagePicker from '@/components/AvatarImagePicker';
import { GeoLocation } from '../common/SelectAddressScreen.types';
import { KeyboardAwareScrollView } from 'react-native-keyboard-controller';
import dayjs from 'dayjs';
import { GOOGLE_MAP_KEY } from '@/config/config';
import { useMMKVBoolean, useMMKVObject } from '@/hooks/useMMkv';
import { UserInfo } from '@/services/api/userApi';
import { Button } from 'tsun-smart-ui';
import NativeToast from '~/specs/NativeToast';
import StringUtils from '@/utils/StringUtils';
import FileUploader from '@/services/FileUploader';
import {
  stationApi,
  StationDTO,
  StationInstallerModel,
  StationTypeModel,
} from '@/services/api/stationApi';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { useSelector } from 'react-redux';
import { RootState } from '@/store';
import { colorScheme } from 'nativewind';
import ArrayUtils from '@/utils/ArrayUtils';
import PermissionUtils, { PERMISSIONS } from '@/utils/PermissionUtils';
import LottieView from 'lottie-react-native';
import WiFiAnimation from '@/components/WiFiAnimation';
import { useDebounceFn } from 'ahooks';

/*
{"location":{"heading":-1,"adCode":"","city":"","timestamp":1750834932909.1821,"longitude":-122.406417,"province":"","cityCode":"","speed":-1,"poiName":"","latitude":37.785834,"street":"","address":"","errorCode":0,"streetNumber":"","accuracy":5,"altitude":0,"country":"","district":""},"coords":{"latitude":37.785834,"longitude":-122.406417,"altitude":0,"accuracy":5,"altitudeAccuracy":0,"heading":-1,"speed":-1},"timestamp":1750834932909.1821}
*/

const fetchTimezoneFromPosition = async (
  position: GeoLocation
): Promise<string | undefined> => {
  const url = `https://maps.googleapis.com/maps/api/timezone/json?location=${
    position.latitude
  },${position.longitude}&timestamp=${dayjs().valueOf()}&key=${GOOGLE_MAP_KEY}`;
  return fetch(url)
    .then((res) => res.json())
    .then((json) => json.timeZoneId ?? undefined)
    .catch((reason) => undefined);
};

type Mode = 'create' | 'edit' | 'preview';

/// 新建电站
const CreatePowerStation = () => {
  const { t } = useTranslation();
  const navigation = useNavigation<NativeStackNavigationProp<any>>();
  const route = useRoute<RouteProp<any>>();
  const station: StationDTO | undefined = route?.params?.station;
  const [image, setImage] = useState<Asset | string | undefined>(
    station?.coverImage
  );
  const [name, setName] = useState(station?.stationName);
  const [detailAddress, setDetailAddress] = useState(station?.detailAddress);
  const [stationTypeIndex, setStationTypeIndex] = useState<number>();
  const [stationTypes, setStationTypes] = useState<StationTypeModel[]>([]);
  const stationTypeNames = useMemo(() => {
    return stationTypes.map((item) => t(item.value));
  }, [stationTypes, t]);
  const stationTypeBottomSheet = useRef<BottomSheetModal>(null);
  const stationInstallerBottomSheet = useRef<BottomSheetModal>(null);
  const [position, setPosition] = useState<GeoLocation | undefined>(() => {
    if (station) {
      return {
        latitude: station.latitude,
        longitude: station.longitude,
        address: station.address,
      };
    }
    return undefined;
  });
  const [timezone, setTimezone] = useState<string | undefined>(
    station?.timezone
  );
  const visualizedTimezome = useMemo(() => {
    if (timezone) {
      const timezoneText = 'tz.' + timezone.replaceAll('/', '.').toLowerCase();
      return t(timezoneText);
    }
    return 'Asia/Shanghai';
  }, [timezone, t]);
  const [stationInstallers, setStationInstallers] = useState<
    StationInstallerModel[]
  >([]);
  const [selectedInstaller, setSelectedInstaller] =
    useState<StationInstallerModel>();
  // const [stationInstallerIndex, setStationInstallerIndex] = useState<number>();
  const [initialLoading, initialTransition] = useTransition();
  const [isSubmiting, setIsSubmiting] = useState(false);
  const isChineseUser = useSelector<RootState, boolean>(
    (state: any) => state.global.isChineseUser
  );
  const [mode, setMode] = useState<Mode>(() => {
    if (station) {
      return 'preview';
    }
    return 'create';
  });

  // let selectedInstaller =
  //   stationInstallerIndex === undefined
  //     ? undefined
  //     : stationInstallers[stationInstallerIndex];
  let selectedStationType =
    stationTypeIndex === undefined ? undefined : stationTypes[stationTypeIndex];

  useEffect(() => {
    if (route.params?.installer) {
      setSelectedInstaller(route.params?.installer);
    }
  }, [route.params?.installer]);

  useEffect(() => {
    let editButton = null;
    let title = t('sys.app.station.create');
    if (mode === 'preview') {
      editButton = (
        <View className="mr-4">
          <Button
            variant="text"
            title={t('userSetting.SecuritySettings.button.update')}
            onPress={() => setMode('edit')}
          />
        </View>
      );
      title = t('mn.station.detail');
    } else if (mode === 'edit') {
      title = t('sys.app.edit.power.station');
    }
    navigation.setOptions({
      headerTitle: title,
      headerRight: () => editButton,
    });
    init();
  }, [navigation, position, mode, t]);

  const init = useCallback(() => {
    initialTransition(() => {
      if (!position) {
        updateCurrentPosition();
      }
      if (ArrayUtils.isEmpty(stationTypes)) {
        stationApi.getStationTypes().then((res) => {
          const stationTypes = res.data?.records;
          if (stationTypes) {
            setStationTypes(stationTypes);
            if (station) {
              const index = stationTypes.findIndex(
                (item) => item.value === station.stationType
              );
              if (index !== -1) {
                setStationTypeIndex(index);
              }
            }
          }
        });
      }

      if (ArrayUtils.isEmpty(stationInstallers)) {
        stationApi.getStationInstallers().then((res) => {
          const stationInstallers = res.data;
          if (stationInstallers) {
            setStationInstallers(stationInstallers);
            if (station) {
              const index = stationInstallers.findIndex(
                (item) => item.code === station.installerCode
              );
              if (index !== -1) {
                // setStationInstallerIndex(index);
                setSelectedInstaller(stationInstallers[index]);
              }
            }
          }
        });
      }
    });
  }, [position]);

  useEffect(() => {
    if (route?.params?.position) {
      setPosition(route?.params?.position);
    }
  }, [route?.params?.position]);

  useEffect(() => {
    if (isChineseUser) {
      setTimezone('Asia/Shanghai');
      return;
    } else {
      if (position) {
        fetchTimezoneFromPosition(position).then((timezone) => {
          setTimezone(timezone);
        });
      } else {
        setTimezone(undefined);
      }
    }
  }, [position, isChineseUser]);

  const updateCurrentPosition = useCallback(async () => {
    // if (Platform.OS === 'android') {
    const status = await PermissionUtils.checkPermission(
      PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION
    );
    // TODO: 没有定位的话，其实用户还能手动搜，所以不考虑展示弹窗，以免打扰用户
    // }
    setLocatingWithReGeocode(true);
    setNeedAddress(true);
    Geolocation.getCurrentPosition(
      (position) => {
        // @ts-ignore
        setPosition(position.location);
      },
      (error) => {}
    );
  }, []);

  const onChangeStationType = useCallback(() => {
    stationTypeBottomSheet.current?.present();
  }, [selectedStationType]);

  const onSelectAddress = useCallback(() => {
    // @ts-ignore
    navigation.navigate('SelectAddress', {
      callback: 'CreatePowerStation',
    });
  }, []);

  const onSelectStationInstallers = useCallback(() => {
    // stationInstallerBottomSheet.current?.present();
    navigation.navigate('InstCode', {
      callbackRouteName: 'CreatePowerStation',
    });
  }, []);

  const { run: debounceSave } = useDebounceFn(() => onSave(), { wait: 300 });

  const onSave = useCallback(async () => {
    let passed = true;
    if (StringUtils.isEmpty(name)) {
      passed = false;
      NativeToast.showToast({
        message: t('sys.app.pls.input.station.name', {
          defaultValue: '请输入电站名称',
        }),
      });
    } else if (!selectedStationType) {
      passed = false;
      NativeToast.showToast({
        message: t('sys.app.pls.select.station.type', {
          defaultValue: '请选择电站类型',
        }),
      });
    } else if (!position) {
      passed = false;
      NativeToast.showToast({
        message: t('sys.app.pls.select.address', {
          defaultValue: '请选择地址',
        }),
      });
    } else if (StringUtils.isEmpty(detailAddress)) {
      passed = false;
      NativeToast.showToast({
        message: t('sys.app.pls.input.detail.address', {
          defaultValue: '请输入详细地址',
        }),
      });
    }
    if (passed) {
      setIsSubmiting(true);
      let avatarUri: string;
      if (!!image && typeof image === 'object') {
        const fileRemoteUri = await FileUploader.uploadImage(image.uri!);
        if (fileRemoteUri) {
          avatarUri = fileRemoteUri;
        } else {
          setIsSubmiting(false);
          return;
        }
      } else {
        avatarUri = image!;
      }
      let editStationObject: StationDTO = {
        id: station?.id,
        stationName: name!,
        address: position?.address ?? '',
        latitude: position!.latitude,
        longitude: position!.longitude,
        detailAddress: detailAddress!,
        timezone: timezone ?? '',
        installerCode: selectedInstaller?.code,
        coverImage: avatarUri,
        stationType: selectedStationType!.value,
      };
      const isEdit = mode === 'edit';
      const api = isEdit ? stationApi.updateStation : stationApi.createStation;
      api(editStationObject)
        .then((response) => {
          if (response.code == 0) {
            if (route.params?.category && !isEdit) {
              navigation.navigate('Scan', {
                station: response.data,
                category: route.params?.category,
              });
            } else {
              setIsSubmiting(false);
              navigation.popTo('Owner', {
                screen: 'summary',
                params: {
                  newStationId: response.data.id,
                },
              });
            }
          }
        })
        .catch((reason) => {
          setIsSubmiting(false);
        });
    }
  }, [
    image,
    name,
    station,
    selectedStationType,
    selectedInstaller,
    detailAddress,
    timezone,
  ]);

  const canEdit = mode !== 'preview';

  return (
    <>
      <View className="flex-1">
        <KeyboardAwareScrollView
          className="flex-1 bg-fill1"
          contentContainerClassName={`px-4 gap-y-4 py-4`}
          keyboardDismissMode="on-drag"
        >
          <View className="gap-4">
            <Text className="text-text2 font-[15px]">
              {t('monitor.statFacade', { defaultValue: '电站封面' })}
            </Text>
            <AvatarImagePicker
              image={image}
              onPickNewImage={setImage}
              preview={mode === 'preview'}
            />
          </View>
          <FormInputField
            label={t('monitor.statName', { defaultValue: '电站名称' })}
            placeholder={t('sys.common.pls.input', {
              defaultValue: '请输入',
            })}
            value={name}
            onChangeValue={setName}
            required={canEdit}
            maxLength={50}
            editable={canEdit}
          />
          <FormSelectField
            label={t('monitor.statType', { defaultValue: '电站类型' })}
            value={
              Boolean(selectedStationType)
                ? t(selectedStationType!.value)
                : null
            }
            placeholder={t('sysrole.please_select', {
              defaultValue: '请选择',
            })}
            onPress={onChangeStationType}
            editable={canEdit}
            required
          />
          <FormSelectField
            label={t('sys.app.address', { defaultValue: '地址' })}
            placeholder={t('sysrole.please_select', {
              defaultValue: '请选择',
            })}
            value={position?.address}
            onPress={onSelectAddress}
            required={canEdit}
            editable={canEdit}
          />
          <FormInputField
            label={t('userSetting.completeAddress', {
              defaultValue: '详细地址',
            })}
            placeholder={t('sys.common.pls.input', {
              defaultValue: '请输入',
            })}
            value={detailAddress}
            onChangeValue={setDetailAddress}
            required={canEdit}
            editable={canEdit}
          />
          <FormInputField
            label={t('sys.app.time.zone', { defaultValue: '时区' })}
            placeholder={t('sys.app.pls.select.timezone', {
              defaultValue: '请选择时区',
            })}
            value={visualizedTimezome}
            onChangeValue={(txt) => {}}
            required={canEdit}
            editable={false}
          />
          <FormSelectField
            label={t('settings.installer', { defaultValue: '安装商' })}
            value={selectedInstaller?.name}
            onPress={onSelectStationInstallers}
            placeholder={t('sysrole.please_select')}
            editable={canEdit}
          />
        </KeyboardAwareScrollView>
        {canEdit && (
          <SafeAreaView
            edges={['left', 'right', 'bottom']}
            className="px-4 py-3 bg-text6 -sm"
          >
            <Button
              title={t('common.confirmButtonText', { defaultValue: '确认' })}
              onPress={debounceSave}
              loading={isSubmiting || initialLoading}
            />
          </SafeAreaView>
        )}
        <SingleSelectBottomSheet
          title={t('monitor.statType', { defaultValue: '电站类型' })}
          options={stationTypeNames}
          selectedIndex={stationTypeIndex ?? -1}
          onSelect={setStationTypeIndex}
          ref={stationTypeBottomSheet}
        />
        {/* <SingleSelectBottomSheet
          title={t('settings.installer', { defaultValue: '安装商' })}
          options={stationInstallers}
          labelKey={'name'}
          selectedIndex={stationInstallerIndex ?? -1}
          onSelect={setStationInstallerIndex}
          ref={stationInstallerBottomSheet}
        /> */}
      </View>
    </>
  );
};

export default React.memo(CreatePowerStation);
